package com.CRApp.controller;

import com.CRApp.pojo.Article;
import com.CRApp.pojo.PostDetailsDTO;
import com.CRApp.pojo.Posts;
import com.CRApp.pojo.Result;
import com.CRApp.pojo.Comment;
import com.CRApp.pojo.CommentDTO;
import com.CRApp.service.PostsService;
import com.CRApp.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;

/**
 * @ClassName: PostsContorller
 * @Author : LuoFan洛樊
 * @Date : 2025/3/29 - 16:02
 * Description : 推文Controller
 */
@RestController
@CrossOrigin
@RequestMapping("/posts")
public class PostsContorller {

    @Autowired
    private PostsService postsService;

    @Autowired
    private FileUploadController fileUploadController;

    //获取推文列表
    @GetMapping("/list")
    public Result<List<Posts>> getPosts(){
        // 从ThreadLocal中获取当前登录用户ID
        Map<String, Object> map = ThreadLocalUtil.get();
        System.out.println(map);
        Integer currentUserId = null;
        if (map != null) {
            currentUserId = (Integer) map.get("id");
        }
        // 即使用户未登录，也可以查看公开的推文
        List<Posts> postsList = postsService.getPostsList(currentUserId);
        return Result.success(postsList);
    }

    //获取推文详情
    @PostMapping("/postDetails")
    public Result<PostDetailsDTO> getPostDetails(@RequestParam Integer postId) {
        PostDetailsDTO postDetails = postsService.getPostDetails(postId);
        return Result.success(postDetails);
    }

    //获取推文评论
    @PostMapping("/comments")
    public Result<List<Comment>> getPostComments(@RequestParam Integer postId) {
        List<Comment> comments = postsService.getPostComments(postId);
        return Result.success(comments);
    }

    //添加评论
    @PostMapping("/addComment")
    public Result<String> addComment(@RequestBody CommentDTO commentDTO) {
        // 从ThreadLocal中获取当前登录用户ID
        Map<String, Object> map = ThreadLocalUtil.get();
        if (map == null) {
            return Result.error("未登录");
        }
        Integer currentUserId = (Integer) map.get("id");

        postsService.addComment(commentDTO, currentUserId);
        return Result.success("评论成功");
    }

    // 发布新推文
    @PostMapping("/addPost")
    public Result<Integer> addPost(
            @RequestParam("title") String title,
            @RequestParam("content") String content,
            @RequestParam("isPublic") Integer isPublic,
            @RequestParam(value = "images", required = false) MultipartFile[] images
    ) {
        try {
            // 1. 获取当前登录用户ID
            Map<String, Object> map = ThreadLocalUtil.get();
            if (map == null) {
                return Result.error("未登录");
            }
            Integer currentUserId = (Integer) map.get("id");

            // 2. 参数校验
            if (title == null || title.trim().isEmpty()) {
                return Result.error("标题不能为空");
            }
            if (content == null || content.trim().isEmpty()) {
                return Result.error("内容不能为空");
            }
            if (images != null && images.length > 6) {
                return Result.error("最多只能上传6张图片");
            }

            // 3. 上传图片到OSS
            List<String> imageUrls = new ArrayList<>();
            if (images != null && images.length > 0) {
                for (MultipartFile image : images) {
                    // 检查图片格式
                    String originalFilename = image.getOriginalFilename();
                    if (originalFilename != null) {
                        String suffix = originalFilename.substring(originalFilename.lastIndexOf(".") + 1).toLowerCase();
                        if (!Arrays.asList("jpg", "jpeg", "png", "gif").contains(suffix)) {
                            return Result.error("只支持jpg、jpeg、png、gif格式的图片");
                        }
                    }
                    // 检查图片大小
                    if (image.getSize() > 5 * 1024 * 1024) { // 5MB
                        return Result.error("单张图片不能超过5MB");
                    }
                    // 上传图片
                    Result<String> uploadResult = fileUploadController.upload(image);
                    if (uploadResult.getCode() == 200) {
                        imageUrls.add(uploadResult.getData());
                    } else {
                        return Result.error("图片上传失败");
                    }
                }
            }

            // 4. 创建推文对象
            Posts post = new Posts();
            post.setTitle(title);
            post.setContent(content);
            post.setCreatorId(currentUserId);
            post.setIsPublic(isPublic);
            post.setCreatedAt(LocalDateTime.now());

            // 5. 保存推文和图片
            Integer postId = postsService.createPost(post, imageUrls);

            return Result.success(postId);
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("发布失败：" + e.getMessage());
        }
    }

    // 检查推文是否已收藏
    @GetMapping("/isCollected")
    public Result<Boolean> checkCollection(@RequestParam Integer postId) {
        // 从ThreadLocal中获取当前登录用户ID
        Map<String, Object> map = ThreadLocalUtil.get();
        if (map == null) {
            return Result.error("未登录");
        }
        Integer currentUserId = (Integer) map.get("id");
        
        boolean isCollected = postsService.isCollected(currentUserId, postId);
        return Result.success(isCollected);
    }

    // 收藏/取消收藏推文
    @PostMapping("/collect")
    public Result<String> toggleCollection(@RequestParam Integer postId) {
        // 从ThreadLocal中获取当前登录用户ID
        Map<String, Object> map = ThreadLocalUtil.get();
        if (map == null) {
            return Result.error("未登录");
        }
        Integer currentUserId = (Integer) map.get("id");
        
        boolean isCollected = postsService.toggleCollection(currentUserId, postId);
        return Result.success(isCollected ? "收藏成功" : "取消收藏成功");
    }

    // 获取用户收藏的推文列表
    @GetMapping("/collections")
    public Result<List<Posts>> getCollections() {
        // 从ThreadLocal中获取当前登录用户ID
        Map<String, Object> map = ThreadLocalUtil.get();
        if (map == null) {
            return Result.error("未登录");
        }
        Integer currentUserId = (Integer) map.get("id");
        
        List<Posts> collections = postsService.getUserCollections(currentUserId);
        return Result.success(collections);
    }

}
